/**
 * @author 0283000106
 * @date 2020年2月23日-下午2:32:37
 */
package com.zte.claa.inficombo.csa.app.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zte.claa.inficombo.csa.app.comm.csif.CSIFCmdBuilder;
import com.zte.claa.inficombo.csa.app.dao.mysql.impl.CameraPhotoDataMapper;
import com.zte.claa.inficombo.csa.app.model.dev.DevBase;
import com.zte.claa.inficombo.csa.app.model.dev.DevTypeModel;
import com.zte.claa.inficombo.csa.app.model.dev.ResourceShadow;
import com.zte.claa.inficombo.csa.app.model.redis.DevMeteData;
import com.zte.claa.inficombo.csa.app.service.huaxiapr.HuaXiaRmPlateRecogService;
import com.zte.claa.inficombo.csa.app.service.huaxiapr.bean.HuaXiaRmRspMsg;
import com.zte.claa.inficombo.csa.app.service.huaxiapr.bean.HuaXiaRmRspMsgCache;
import com.zte.claa.inficombo.csa.app.service.photo.bean.CameraPhotoData;
import com.zte.claa.inficombo.csa.app.service.resrpt.ResIndexDataRptService;
import com.zte.claa.inficombo.csa.app.service.rptparse.ParserContainer;
import io.swagger.annotations.ApiOperation;

/**
 * @author 0283000106
 * 
 * 该controller仅用于接收华夏相机RM车牌识别一体机发送的HTTP请求.
 *
 */

@RestController
@RequestMapping("/inficombo")
public class HuaXiaRmPlateRecogController extends BaseController {	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	// logger
	private Logger logger = LoggerFactory.getLogger(HuaXiaRmPlateRecogController.class);
	
	@Autowired
	private ResIndexDataRptService resDataRptService;
	
	@Autowired
	private HuaXiaRmPlateRecogService huaXiaService;
	
	@Autowired
	private ParserContainer parserContainer;
	
	@Autowired
	private CameraPhotoDataMapper photoDataMapper;
	
	
	
	/**
	 * 接收华夏RM车牌识别一体机车牌识别信息
	 *  
	 * ctx+'/inficombo/hxrmplaterecog';	   
	 */
	@ApiOperation(value = "车牌识别信息", notes = "")
	@RequestMapping(value={"/hxrmplaterecog"}, method = RequestMethod.POST)
	@ResponseBody
//	public HuaXiaRmRspMsg receiveHuaXiaRmPlateRecogMsg(@RequestParam Map<String, String> params, HttpServletResponse response) throws Exception{
////		Map<String, String[]> params = request.getParameterMap();
//		logger.info("Receive huaxia rm plate recog msg info: " + params);
//		String type = params.get("type"); 
//		String cam_id = params.get("cam_id"); 
//		HuaXiaRmRspMsg hxRmRspMsg = null;
//		if(type.equals("online") || type.equals("offline")){
//			hxRmRspMsg = dealPlateRecogMsg(params);
//		}else if(type.equals("heartbeat")){
//			hxRmRspMsg = dealHeartBeatMsg(params);
//		}else if(type.equals("ioinput")){
//			hxRmRspMsg = dealIoinputMsg(params);
//		}else{
//			hxRmRspMsg = null;
//		}
//		response.setContentType("application/json;charset=UTF-8");
//		response.setCharacterEncoding("UTF-8");
//		response.setStatus(HttpServletResponse.SC_OK);
//		logger.info("[*^_^*]Response HuaXiaRmPlateRecog message ok,type:"+type+",cam_id:"+cam_id+",hxRmRspMsg:"+hxRmRspMsg);		
//		return hxRmRspMsg;
//	}	
	
	public HuaXiaRmRspMsg receiveHuaXiaRmPlateRecogMsg(@RequestParam Map<String, String> params) throws Exception{
		logger.info("Receive huaxia rm plate recog msg info: " + params);
		String type = params.get("type"); 
		String cam_id = params.get("cam_id"); 
		HuaXiaRmRspMsg hxRmRspMsg = null;
		if(type.equals("online") || type.equals("offline")){
			hxRmRspMsg = dealPlateRecogMsg(params);
		}else if(type.equals("heartbeat")){
			hxRmRspMsg = dealHeartBeatMsg(params);
		}else if(type.equals("ioinput")){
			hxRmRspMsg = dealIoinputMsg(params);
		}else{
			hxRmRspMsg = null;
		}
		logger.info("[*^_^*]Response HuaXiaRmPlateRecog message ok,type:"+type+",cam_id:"+cam_id+",hxRmRspMsg:"+hxRmRspMsg);		
		return hxRmRspMsg;
	}	
	
	private HuaXiaRmRspMsg dealPlateRecogMsg(Map<String, String> params) throws Exception{
		/*
		 *  type=online&mode=5&plate_num= 京 A12345&plate_color= 蓝 色&plate_val=true&confidence=25& 
		 *  car_logo= 丰 田 & car_sublogo= 卡 罗 拉 &car_color= 白 色&vehicle_type= 轿 车&
		 *  start_time=1436509947&park_id=2&cam_id=0001aa00000d&
			cam_ip=192.168.55.100&vdc_type=in&is_whitelist=true&
			triger_type=video&picture=<BASE64 全 景图 >&
			closeup_pic=<BASE64 车牌特写图>
		 */
		logger.info("Receive plate recogdata info String: " + params);
		String type = params.get("type"); 
		params.get("mode"); 
		params.get("plate_num"); 
		params.get("plate_color"); 
		params.get("plate_val"); 
		params.get("confidence"); 
		params.get("car_logo"); 
		params.get("car_sublogo"); 
		params.get("car_color"); 
		params.get("vehicle_type"); 
		String start_time = params.get("start_time"); 
		params.get("park_id"); 
		String cam_id = params.get("cam_id"); 
		params.get("cam_ip"); 
		params.get("vdc_type"); 
		params.get("is_whitelist"); 
		params.get("triger_type"); 
		String picture = params.get("picture");          //BASE64
		String closeup_pic = params.get("closeup_pic");  //BASE64
		
		Map<String, Object> mdata = new HashMap<String, Object>();
		DevMeteData meteData = new DevMeteData();
		if(null == cam_id || "".equals(cam_id)){
			// 考虑下cam_id为空时，是否需要下发应答响应
			logger.info("dealPlateRecogMsg, cam_id is null!");
			return null;
		}
		String deveui = cam_id;
		if(null!=start_time && !"".equals(start_time)){
	        long second = Long.parseLong(start_time);
	        Date d = new Date();
	        d.setTime(second *1000);
	        meteData.setRpttime(new Timestamp(d.getTime()));
		}else{
			meteData.setRpttime(new Timestamp((new Date()).getTime()));
		}
		
		ResourceShadow devbase = this.parserContainer.getCacheManager().getRes(deveui);
		if(null == devbase){
			// 考虑devbase对象为空时，是否需要下发应答响应
			logger.error("dealPlateRecogMsg, Can not get devbase, deveui:"+deveui);
			return null;
		}
		
        String devTypeId = devbase.getRestype();
		DevTypeModel dtm = this.parserContainer.getCacheManager().getDevTypeModel(devTypeId);
		if(dtm == null || dtm.getDmList() == null){
			logger.error("dealPlateRecogMsg, Can not get datamodel for devtype:"+devTypeId);
			return null;
		}
		
		String photoid = ""+Math.abs(UUID.randomUUID().getLeastSignificantBits());
		String pictureid = "QJ"+photoid;
		String closeuppicid = "TX"+photoid;
        for (Map.Entry<String, String> entry : params.entrySet()) {
        	String fldname = entry.getKey();
        	String fldval = entry.getValue();
        	if(!fldname.equals("picture") && !fldname.equals("closeup_pic")){
        		mdata.put(fldname, fldval);
        	}
        }
        mdata.put("pictureid", pictureid);
        mdata.put("closeuppicid", closeuppicid);
        
		meteData.setAppeui("");
		meteData.setDeveui(devbase.getResid());
		meteData.setDevname(devbase.getResname());
		meteData.setDevtype(devTypeId);
		meteData.setPort("0");
		meteData.setProjectid(devbase.getProjectid());
		meteData.setMdata(mdata);
		
		// 持久化数据
		this.resDataRptService.submitResIndexData(meteData);
		
		// 保存图片
		CameraPhotoData camPhotoData = new CameraPhotoData();
        camPhotoData.setDeveui(deveui);
        camPhotoData.setPhototype(1); //1：jpg
        camPhotoData.setProjectid(devbase.getProjectid());
        
        // 插入全景图片数据       
        camPhotoData.setPhotoid(pictureid);
		picture = picture.replace("-", "+");
		picture = picture.replace("_", "/");
		picture = picture.replace(".", "=");
		byte[] allbytes = CSIFCmdBuilder.base64Decode(picture);
		camPhotoData.setPhoto(allbytes);
        photoDataMapper.addCameraPhotoData(camPhotoData);
        
        // 插入车牌特写图片数据
        camPhotoData.setPhotoid(closeuppicid);
        closeup_pic = closeup_pic.replace("-", "+");
        closeup_pic = closeup_pic.replace("_", "/");
        closeup_pic = closeup_pic.replace(".", "=");
		allbytes = CSIFCmdBuilder.base64Decode(closeup_pic);
		camPhotoData.setPhoto(allbytes);
        photoDataMapper.addCameraPhotoData(camPhotoData);
	        
		// 处理应答消息
		HuaXiaRmRspMsg hxRmRspMsg = this.huaXiaService.getHuaXiaRspMsg(deveui, type);
		logger.info("[*^_^*]Response HuaXiaPlateRecog message ok: "+hxRmRspMsg);		
		return hxRmRspMsg;
	}		
	
	private HuaXiaRmRspMsg dealHeartBeatMsg(Map<String, String> params) throws Exception{
		/*
		 *  type=heartbeat&mode=5&interval=10&park_id=0&
		 *  cam_id=18030006f501&cam_ip=192.168.16.217
		 */
		logger.info("Receive heartbeat message info String: " + params);
		String type = params.get("type"); 
		params.get("mode"); 
		params.get("interval"); 
		params.get("park_id"); 
		String cam_id = params.get("cam_id"); 
		params.get("cam_ip");
//		logger.info("Receive heartbeat message info,cam_id: " + cam_id);
		Map<String, Object> mdata = new HashMap<String, Object>();
		DevMeteData meteData = new DevMeteData();
		if(null == cam_id || "".equals(cam_id)){
			// 考虑下cam_id为空时，是否需要下发应答响应
			logger.info("dealHeartBeatMsg, cam_id is null!");
			return null;
		}
		String deveui = cam_id;
		ResourceShadow devbase = this.parserContainer.getCacheManager().getRes(deveui);
		if(null == devbase){
			// 考虑devbase对象为空时，是否需要下发应答响应
			logger.error("dealHeartBeatMsg, Can not get devbase, deveui:"+deveui);
			return null;
		}
		
        String devTypeId = devbase.getRestype();
		DevTypeModel dtm = this.parserContainer.getCacheManager().getDevTypeModel(devTypeId);
		if(dtm == null || dtm.getDmList() == null){
			logger.error("dealHeartBeatMsg, Can not get datamodel for devtype:"+devTypeId);
			return null;
		}
		
        for (Map.Entry<String, String> entry : params.entrySet()) {
        	String fldname = entry.getKey();
        	String fldval = entry.getValue();
        	mdata.put(fldname, fldval);
        }        
		meteData.setAppeui("");
		meteData.setDeveui(devbase.getResid());
		meteData.setDevname(devbase.getResname());
		meteData.setDevtype(devTypeId);
		meteData.setPort("0");
		meteData.setProjectid(devbase.getProjectid());
		meteData.setMdata(mdata);
		
		// 持久化数据
//		this.resDataRptService.submitResIndexData(meteData);
		        
		// 处理应答消息
		HuaXiaRmRspMsg hxRmRspMsg = this.huaXiaService.getHuaXiaRspMsg(deveui, type);
		logger.info("[*^_^*]Response HuaXiaHeartBeat message ok: "+hxRmRspMsg);		
		return hxRmRspMsg;
	}	
	
	private HuaXiaRmRspMsg dealIoinputMsg(Map<String, String> params) throws Exception{
		/*
		 * type=ioinput&mode=5&park_id=2&cam_id=0001aa00000d&
		 * vehicle_type= 轿 车&ionum=1&iostatus=0&start_time=1436509947
		 */
		logger.info("Receive ioinput message info String: " + params);
		String type = params.get("type"); 
		params.get("mode"); 		
		params.get("park_id"); 
		String cam_id = params.get("cam_id"); 
		params.get("vehicle_type"); 
		params.get("ionum"); 
		params.get("iostatus"); 
		String start_time = params.get("start_time"); 
		
		Map<String, Object> mdata = new HashMap<String, Object>();
		DevMeteData meteData = new DevMeteData();
		if(null!=cam_id && !"".equals(cam_id)){
			// 考虑下cam_id为空时，是否需要下发应答响应
			return null;
		}
		String deveui = cam_id;
		DevBase devbase = this.parserContainer.getCacheManager().getDev(deveui);
		if(null == devbase){
			// 考虑devbase对象为空时，是否需要下发应答响应
			logger.error("dealIoinputMsg, Can not get devbase, deveui:"+deveui);
			return null;
		}
		
        String devTypeId = devbase.getDevType();
		DevTypeModel dtm = this.parserContainer.getCacheManager().getDevTypeModel(devTypeId);
		if(dtm == null || dtm.getDmList() == null){
			logger.error("dealIoinputMsg, Can not get datamodel for devtype:"+devTypeId);
			return null;
		}
		
		if(null!=start_time && !"".equals(start_time)){
	        long second = Long.parseLong(start_time);
	        Date d = new Date();
	        d.setTime(second *1000);
	        meteData.setRpttime(new Timestamp(sdf.parse(start_time).getTime()));
		}else{
			meteData.setRpttime(new Timestamp((new Date()).getTime()));
		}
		
        for (Map.Entry<String, String> entry : params.entrySet()) {
        	String fldname = entry.getKey();
        	String fldval = entry.getValue();
        	mdata.put(fldname, fldval);
        }        
		meteData.setAppeui(devbase.getAppEui());
		meteData.setDeveui(devbase.getDevEui());
		meteData.setDevname(devbase.getDevName());
		meteData.setDevtype(devTypeId);
		meteData.setPort("0");
		meteData.setProjectid(devbase.getProjectId());
		meteData.setMdata(mdata);
		
		// 持久化数据
//		this.resDataRptService.submitResIndexData(meteData);
		        
		// 处理应答消息
		HuaXiaRmRspMsg hxRmRspMsg = this.huaXiaService.getHuaXiaRspMsg(deveui, type);
		logger.info("[*^_^*]Response HuaXiaIoinput message ok: "+hxRmRspMsg);		
		return hxRmRspMsg;
	}	
}
